import { genPlaceholder} from '../util'
import { findComponentUpward } from '@src/util/assist';
import _ from 'lodash';
import { getRootWindow } from '@src/util/dom'

const FormMixin = {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    field: {
      type: Object,
      default: () => ({})
    },
    placeholder: {
      type: String,
      default() {
        return genPlaceholder(this.field);
      }
    },
  },
  computed: {
    /** 
    * @description 不允许修改
    * 1.有默认值
    * 2.且 设置不允许修改
    */
    disabled() {
      let field = this.field;
      return (
        field.disabled || (
          field.setting 
            && field.setting.defaultValueConfig 
            && !!field.setting.defaultValueConfig.isNotModify 
            && !!field.defaultValue
        )
      )
    },
    formBuilderComponent() {
      return findComponentUpward(this, 'form-builder')
    },
    /**
     * @description: 获取当前表单的所有value
     */
    formValue() {
      let parent = findComponentUpward(this, 'form-builder');
      let form = parent?.value || {};
      return form;
    },
    /**
     * @description: 获取当前表单的所有fields
     */
    fields() {
      let parent = findComponentUpward(this, 'form-builder');
      let fields = parent?.fields || [];
      return fields;
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    },
    /**
     * @description 获取表单dom
     */
    textareaRef() {
      return this.$refs.textareaRef;
    }
  },
  data() {
    return {
      getFirstHeightStatus: true, // 第一次获取textarea默认高度状态控制
      getHeight: 0 // 获取textarea的高度
    }
  },
  watch: {
    field(newValue) {
      this.addFieldEvent();
    },
    value:{
      deep: true,
      handler() {
        this.$el.dispatchEvent(new CustomEvent('form.validate', {bubbles: true}));
      }
    }
  },
  methods: {
    addFieldEvent() {
      // 触发注册事件，用于注册字段到外层 FormItem 组件，和 FormBuilder 组件
      let params = {value: this.getValue, fieldName: this.field.fieldName, field: this.field};
      let event = new CustomEvent('form.add.field', {detail: params, bubbles: true})
      this.$nextTick(() => this.$el.dispatchEvent(event));
    },
    dispatchRemoveFieldEvent() {
      // 注册解绑事件，用于解绑组件
      let params = {fieldName: this.field.fieldName}
      let event = new CustomEvent('form.remove.field', {detail: params, bubbles: true})
      this.$el.dispatchEvent(event)
    },
    /** 获取当前组件的值，验证用 */
    getValue(){
      return this.value;
    },
    input(event){
      this.inputForValue(event.target.value)
      if (this.textareaRef) {
        this.autoResize()
      }
    },
    inputForValue(value){
      let oldValue = null;
      let newValue = value;
      
      // 远程验证事件处理
      this.remoteValidateHandler()
      
      this.$emit('update', {newValue, oldValue, field: this.field});
      this.$emit('input', newValue);
    },
    autoResize() {
      if (this.getFirstHeightStatus) {
        this.getHeight = this.textareaRef?.offsetHeight;
        this.getFirstHeightStatus = false
      }
      const defaultHeight = this.getHeight
      const maxHeight = 320
      this.textareaRef.style.height = `${defaultHeight}px`;
      const contentHeight = this.textareaRef.scrollHeight;
      if (contentHeight > defaultHeight && contentHeight <= maxHeight) {
        this.textareaRef.style.height = `${contentHeight}px`;
        this.textareaRef.style.overflowY = 'hidden';
      } else if (contentHeight > maxHeight) {
        this.textareaRef.style.height = maxHeight + 'px';
        this.textareaRef.style.overflowY = 'auto';
      } else {
        this.textareaRef.style.height = defaultHeight + 'px';
      }
    },
    remoteValidateHandler() {
      if (!this.formBuilderComponent) return
      
      let { remoteValidateData = {} } = this.formBuilderComponent
      let { field } = remoteValidateData
      let { fieldName } = this.field
      
      if (field !== fieldName) {
        this.formBuilderComponent.outsideSetRemoteValidateData({
          field: fieldName,
          validateFunc: null,
        })
      }
    },
    // 校验子表单重复性值表单
    repeatRemoteValidate(currentSparepartIndex) {
      let repeatField = {};
      try {
        for (let i = 0; i < this.checkFieldMap.length; i++) {
          let fieldName = this.checkFieldMap[i].fieldName;
          let fieldValue = this.form[fieldName];
          // 编辑表单删除当前表单
          let needRepeatFieldValue = _.cloneDeep(this.value);
          if (currentSparepartIndex !== null) {
            needRepeatFieldValue.splice(currentSparepartIndex, 1);
          }
          let isRepeat = false;
          for (let i = 0; i < needRepeatFieldValue.length; i++) {
            let needRepeatValue = needRepeatFieldValue[i][fieldName];
            // 存在且不可重复
            if (needRepeatValue && needRepeatValue == fieldValue) {
              isRepeat = true;
              repeatField = this.checkFieldMap[i];
              break;
            }
          }
          if (isRepeat) {
            repeatField = this.checkFieldMap[i];
            break;
          }
        }
      } catch (error) {
        console.log(error);
      }
      if (JSON.stringify(repeatField) !== '{}') {
        return `${this.field.displayName}【${repeatField.displayName}】${this.$t('common.form.tip.filedIsRepeatTips')}`;
      } else {
        return '';
      }
    }
  },
  mounted(){
    this.addFieldEvent();
  },
  beforeDestroy() {
    this.dispatchRemoveFieldEvent()
  },
  destroyed(){
    this.dispatchRemoveFieldEvent()
  }
};

export default FormMixin;
